/*
 * Projet Java / UML -- Trombinoscope - Février / Avril 2012
 * Virginie Messe -- William Huber
 */
package mvc_controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import mvc_model.Personne;
import mvc_model.Promotion;
import outils.PersonneDAO;
import outils.PromotionDAO;

/**
 *
 * @author Virginie Messe & William Huber
 */
public class MainServlet extends HttpServlet {
    
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public void processRequest (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException{
        Class.forName("com.mysql.jdbc.Driver");
        String choix_action = request.getParameter("action");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        if (choix_action == null) {
            choix_action = "afficher_trombi";
        }
        try {
            if (choix_action.equals("Valider")) 
            {
                doCheckAuthentification(request, response);
            }
            
            else if (choix_action.equals("afficher_trombi")) 
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher("trombidisplay.jsp");
                dispatcher.forward(request, response);
                
            }
            else if (choix_action.equals("afficher_admin")) 
            {
                // Niveau d'accessLevel suffisant
                if (request.getSession().getAttribute("user_accessLevel").equals(2)) 
                {
                    RequestDispatcher dispatcher = request.getRequestDispatcher("panneauAdmin.jsp");
                    dispatcher.forward(request, response);
                }
                else 
                {
                    // Niveau d'administration insuffisant
                    // Mettre une page d'erreur ?
                    RequestDispatcher dispatcher = request.getRequestDispatcher("trombidisplay.jsp");
                    dispatcher.forward(request, response);
                }
            }
                    
           
            else if (choix_action.equals("afficher_profil")) 
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher("monCompte.jsp");
                dispatcher.forward(request, response);
            
            }
            else if (choix_action.equals("modifier_profil"))
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher("modifierProfil.jsp");
                dispatcher.forward(request, response);
            }
            else if(choix_action.equals("Enregistrer"))
            {
                doUploaderProfil(request, response);
                RequestDispatcher dispatcher = request.getRequestDispatcher("trombidisplay.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("afficher_personne"))
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher("afficherPersonne.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("creation_fiche_etudiant"))
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher("creationEtudiant.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("Enregistrement"))
            {
                String login = request.getParameter("login");
                Personne p = new Personne();
                RequestDispatcher dispatcher = null;
                if (p.isLoginExistant(login)){
                    dispatcher = request.getRequestDispatcher("erreurLogin.jsp");
                }
                else {
                   doCreationFiche(request, response);
                    dispatcher = request.getRequestDispatcher("trombidisplay.jsp");
                }
                
                    dispatcher.forward(request, response);
                
            }
            else if (choix_action.equals("Rechercher")){
                RequestDispatcher dispatcher = request.getRequestDispatcher("afficherPersonne.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("creation_prom"))
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher("creationPromo.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("Validation"))
            {
                doCreationPromo(request, response);
                RequestDispatcher dispatcher = request.getRequestDispatcher("panneauAdmin.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("rechercher_nom"))
            {
                String nom_r = request.getParameter("nom_recherche");
                if (nom_r != null) {
                    RequestDispatcher dispatcher = request.getRequestDispatcher("resultRecherche.jsp");
                    dispatcher.forward(request, response);
                }
                else 
                {
                    RequestDispatcher dispatcher = request.getRequestDispatcher("erreurRechercheNom.jsp");
                    dispatcher.forward(request, response);
                }
                
            }
            else if (choix_action.equals("supprimer_compte")){
                doSuppressionCompte(request, response);
                RequestDispatcher dispatcher = request.getRequestDispatcher("trombidisplay.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("supprimer_promo")){
                RequestDispatcher dispatcher = request.getRequestDispatcher("modifPromo.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("modifier_promo")){
                RequestDispatcher dispatcher = request.getRequestDispatcher("modifPromo.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("Modifier")){
                RequestDispatcher dispatcher = request.getRequestDispatcher("modificationPromo.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("Soumettre")){
                doUpdatePromo(request, response);
                RequestDispatcher dispatcher = request.getRequestDispatcher("panneauAdmin.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("Supprimer")){
                doSuppressionPromo(request, response);
                RequestDispatcher dispatcher = request.getRequestDispatcher("panneauAdmin.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("Retour")){
                RequestDispatcher dispatcher = request.getRequestDispatcher("panneauAdmin.jsp");
                dispatcher.forward(request, response);
            }
            else if (choix_action.equals("deconnecter")) 
            {
                // Nettoyer les infos du compte ?
                RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
                dispatcher.forward(request, response);
            
            }
           
        } catch (Exception e) {
            request.setAttribute("e", e);
            RequestDispatcher dispatcher = request.getRequestDispatcher("erreur.jsp");
            dispatcher.forward(request, response);    
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "La servlet principale du projet Trombinoscope. Agit en tant "
                + "que contrôleur dans notre modèle.";
    }// </editor-fold>
    
    // Vérfication du couple login / mot de passe
    public void doCheckAuthentification(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException {
        
        Class.forName("com.mysql.jdbc.Driver");
        
        //Récupération du login et du mot de passe
        String login = request.getParameter("login");
        String password = request.getParameter("password");
        
        //Création d'une personne
        Personne p = new Personne ();
        p= p.checkAuthentification(login, password);
        if (login != null && !login.equals("") && password != null && !password.equals("")) 
        {
            if (p != null) 
            {
                request.getSession().setAttribute("user_id", p.getId());
                request.getSession().setAttribute("user_prenom", p.getPrenom());
                request.getSession().setAttribute("user_nom", p.getNom());
                request.getSession().setAttribute("user_accessLevel", p.getAccessLevel());
     
                RequestDispatcher dispatcher = request.getRequestDispatcher("trombidisplay.jsp");
                dispatcher.forward(request, response);
            } 
            else
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher("erreur.jsp");
                dispatcher.forward(request, response);
            }
        }
        else {
            RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
            dispatcher.forward(request, response);
                }
    }
    
    public void doUploaderProfil (HttpServletRequest request, HttpServletResponse response){
        int id = 0;
        Personne p = new Personne();
        
         //Recherche de la personne
            id = Integer.parseInt(request.getParameter("idProfil"));
            PersonneDAO pDAO = new PersonneDAO();
            p = pDAO.find(id);
        
        
        //Récupération des valeurs modifiées
        String nom = request.getParameter("nom");
        String prenom = request.getParameter("prenom");
        String cheminPhoto = request.getParameter("cheminPhoto");
        String adresse = request.getParameter("adresse");
        String codePostal = request.getParameter("codePostal");
        String ville = request.getParameter("ville");
        String telephone = request.getParameter("telephone");
        String email = request.getParameter("email");
        String dateNaissance = request.getParameter("dateNaissance");
        String sexe = request.getParameter("sexe");
        
        p.update(id, nom, prenom, cheminPhoto, adresse, codePostal, ville, telephone, email, dateNaissance, sexe);
    }
    
    public void doCreationFiche (HttpServletRequest request, HttpServletResponse response) throws IOException{
        Personne p = new Personne();
        
        String promo = request.getParameter("promo");
        if (promo == null) {
            promo = "01";
        }
        int int_promo = Integer.parseInt(promo);
        
        
         //Récupération des valeurs modifiées
        String nom = request.getParameter("nom");
        String prenom = request.getParameter("prenom");
        String statut = request.getParameter("statut");
        int stat = Integer.parseInt(statut);
        String cheminPhoto = request.getParameter("cheminPhoto");
        String adresse = request.getParameter("adresse");
        String codePostal = request.getParameter("codePostal");
        String ville = request.getParameter("ville");
        String telephone = request.getParameter("telephone");
        String email = request.getParameter("email");
        String login = request.getParameter("login");
        String password = request.getParameter("password");
        String dateNaissance = request.getParameter("dateNaissance");
        String sexe = request.getParameter("sexe");
        
        p.insert(nom, prenom, stat, cheminPhoto, adresse, codePostal, ville, telephone, email, login, password, int_promo, dateNaissance, sexe);
        
        
    }
    
    public void doSuppressionCompte (HttpServletRequest request, HttpServletResponse response){
        String idString = request.getParameter("idSuppression");
        int idessai = Integer.parseInt(idString);
        Personne p = new Personne();
        
        p.delete(idessai);
    }
    
    public void doCreationPromo (HttpServletRequest request, HttpServletResponse response){
        Promotion p = new Promotion();
        
        //Récupération des valeurs modifiées
        String classe = request.getParameter("classe");
        String anneeScolaire = request.getParameter("anneeScolaire");
        String statut = request.getParameter("statut");
        int stat = Integer.parseInt(statut);
        String email = request.getParameter("email");
        
        
        p.insert(classe, anneeScolaire, stat, email);
    }
    
    public void doSuppressionPromo (HttpServletRequest request, HttpServletResponse response){
        String promo = request.getParameter("promo");
        if (promo == null) {
            promo = "01";
        }
        int int_promo = Integer.parseInt(promo);
        Promotion p = new Promotion();
        
        p.delete(int_promo);
    }
    
    public void doUpdatePromo (HttpServletRequest request, HttpServletResponse response){
        int id = 0;
        Promotion p = new Promotion();
        
        //Recherche de la promotion
        String promo = request.getParameter("idPromo");
        id = Integer.parseInt(promo);
        PromotionDAO pDAO = new PromotionDAO();
        p = pDAO.find(id);
        
        
        //Récupération des valeurs modifiées
        String classe = request.getParameter("classe");
        String anneeScolaire = request.getParameter("anneeScolaire");
        int statut = Integer.parseInt(request.getParameter("statut"));
        String email = request.getParameter("email");
        
        p.update(id, classe, anneeScolaire, statut, email);
    }
    
    
     
   
}
